package com.guinea.core.service;

import java.util.Iterator;
import java.util.List;
import java.util.Set;

import net.sf.navigator.menu.MenuComponent;
import net.sf.navigator.menu.MenuRepository;

import org.hibernate.Criteria;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import com.guinea.core.Constants;
import com.guinea.system.entity.Menu;
import com.guinea.system.entity.MenuRoleRel;
import com.guinea.system.service.MenuService;

public class MyMenuService extends MenuService{

	public MenuRepository getRepository(){
		List menus = getValidSerial();
		MenuRepository repository = new MenuRepository();
		
		MenuComponent root = new MenuComponent();
		root.setName("root");
		root.setTitle("ROOT");
		repository.addMenu(root);
		
		for (Iterator iter = menus.iterator(); iter.hasNext();) {
			Menu menu = (Menu) iter.next();
			Menu parent = null;
			if(menu.getParentId() != null)
				parent = (Menu)getEntityDao().get(menu.getParentId());
			MenuComponent parentMenu = null;
			if(parent != null)
				parentMenu = repository.getMenu(parent.getMenuName());
			if(parentMenu == null ){
				if(parent != null && !"root".equalsIgnoreCase(parent.getMenuName())){
					parentMenu = createMenuComponent(parent);
					repository.addMenu(parentMenu);
				}else{
					parentMenu = root;
				}
			}
			MenuComponent mc = createMenuComponent(menu);
			mc.setParent(parentMenu);
			repository.addMenu(mc);
		}
		
		return repository;
	}
	private MenuComponent createMenuComponent(Menu menu){
		MenuComponent mc = new MenuComponent();
		mc.setName(menu.getMenuName());
		mc.setTitle(menu.getTitle());
		String type = menu.getMenuType();
		if("action".equalsIgnoreCase(type)){
			mc.setAction(menu.getMenuUrl());
		}
		if("".equalsIgnoreCase(type)){
			mc.setForward(menu.getMenuUrl());
		}
		if("".equalsIgnoreCase(type)){
			mc.setLocation(menu.getMenuUrl());
		}
		if("page".equalsIgnoreCase(type)){
			mc.setPage(menu.getMenuUrl());
		}
		if("".equalsIgnoreCase(type)){
			mc.setTarget(menu.getMenuUrl());
		}
		if("".equalsIgnoreCase(type)){
			mc.setUrl(menu.getMenuUrl());
		}
		Set menuRoleRels = menu.getMenuRoleRels();
		String  roleString = "";
		for (Iterator iter = menuRoleRels.iterator(); iter.hasNext();) {
			MenuRoleRel menuRoleRel = (MenuRoleRel) iter.next();
			roleString += menuRoleRel.getRole().getId().longValue();
			if(iter.hasNext()) roleString += ",";
		}
		if(!roleString.trim().equals(""))
			mc.setRoles(roleString);
		return mc;
	}
	
	/**
	 * 获取全部标记可用对象,顺序排列
	 */
	public List getValidSerial(){
		Criterion criterion= Restrictions.eq(Constants.STATUS_PROPERTY, Constants.STATUS_VALID);
		Criteria c = getEntityDao().createCriteria(criterion);
		c.addOrder(Order.asc("parentId"));
		c.addOrder(Order.asc("serial"));
		return c.list();
	}
}
